﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Radiation___IM
{
    public class RSAManager
    {
        public static RSAManager _manager;

        public static void Init()
        {
            _manager = new RSAManager();
        }

        public static RSAManager Instance
        {
            get
            {
                return _manager;
            }
        }

        // Dynamic part

        private RSAParameters m_private_key;
        private RSAParameters m_public_key;
        private string m_public_key_xml;

        private RSACryptoServiceProvider m_encrypt;
        private RSACryptoServiceProvider m_decrypt;

        public string m_server_public_key;

        public string XMLPublicKey
        {
            get
            {
                return m_public_key_xml;
            }
        }

        public RSAManager()
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(2048);
            this.m_private_key = provider.ExportParameters(true);
            this.m_public_key = provider.ExportParameters(false);
            this.m_public_key_xml = provider.ToXmlString(false);
            this.m_decrypt = provider;
        }

        public string Encrypt(string to_encrypt)
        {
            string final = "";

            try
            {
                if (m_encrypt == null)
                {
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                    RSA.FromXmlString(this.m_server_public_key);
                    m_encrypt = RSA;
                }
                final = Convert.ToBase64String(m_encrypt.Encrypt(UnicodeEncoding.Unicode.GetBytes(to_encrypt), true));
            }
            catch (Exception e) { }

            return final;
        }

        public string Decrypt(string to_decrypt)
        {
            string final = "";

            try
            {
                final = UnicodeEncoding.Unicode.GetString(m_decrypt.Decrypt(Convert.FromBase64String(to_decrypt), true));
            }
            catch (Exception e) { }

            return final;
        }
    }
}
